<?php
require_once "class/char/Player.php";
/**
 * Authenticator class, verify users and passwords.
 * @static
 * @package meta
 * @author alcaitiff
 */
class Authenticator
{
    private $password=null;
    private $timestamp=0;
    /**
     * Authenticate an user
     * @static
     * @param string $id
     * @param int $time
     * @param string $key
     * @return Player
     */
	public function authenticate($id,$time,$key){
		if($id!=null and $time!=null and $key!=null){
			$this->retrieveUserData($id);
			if($this->password!=null){
				if($time<=$this->timestamp){
						MessageSystem::addErrorMessage( 'An error on your identication occurred. '.
                                                        'The error is invalid time: '.$time.' your next valid time is '.(1+$this->timestamp).'. '.
                                                        'This may occour beacuse another client send us a command with your ID. '.
                                                        'Please close all other clients or AMUD browser tabs and try again.');
				}elseif($key==sha1($id.$this->password.$time)){
					$player = new Player($id);
					MessageSystem::setUser($player->charId);
                    MessageSystem::addDebugMessage('Saving time:'.$time.' For user:'.$id);
					$this->saveUserTime($id,$time);
					return $player;					
				}else{
					MessageSystem::addErrorMessage('Incorrect login or password');
				}
			}else{
				MessageSystem::addErrorMessage('Incorrect login or password');
			}
		}
		MessageSystem::addDebugMessage('Authentication Fail { id:'.$id.',time:'.$time.',key:'.$key.'}');
		return new Player();		
	}
    //***********************************************************************************************************
    //					DATABASE METHODS
    //***********************************************************************************************************

    /**
     * Get an user password
     * @param string $id
     * @return void
     */
	private function retrieveUserData($id){
		$dbo=new DB();
		$db=$dbo->db;
		$stmt = $db->prepare("SELECT password,UNIX_TIMESTAMP(timestamp) FROM users WHERE user = ?");
	    $stmt->bind_param("s", $id);
	    $stmt->execute();
    	$stmt->bind_result($this->password,$this->timestamp);
    	$stmt->fetch();
		$stmt->close(); 
	}
    /**
     * Save an user timestamp
     * @param string $id
     * @param int $time
     * @return void
     */
	private function saveUserTime($id,$time){
		$dbo=new DB();
		$db=$dbo->db;
		$stmt = $db->prepare("UPDATE users SET timestamp = FROM_UNIXTIME(?) WHERE user = ?");
	    $stmt->bind_param("is", $time, $id);
	    $stmt->execute();
    	$stmt->fetch();
		$stmt->close(); 
	}

}